Config =
  'apiRoot': 'http://172.27.35.5:8080/net-team'
  'page_size': 5
  'page_url_param': 'page'
  '男': 0
  '女': 1



class Model
  '''model基类'''
  url: ''
  new_url: ''
  update_url: ''
  fetch_url: ''
  delete_url: ''

  options:
    crossDomain: true
    dataType: 'json'

  new: (options) =>
    _options =
      type: 'POST'
    @_curd(_options, options)

  update: (options) =>
    _options =
      type: 'PUT'
    @_curd(_options, options)

  fetch: (options) =>
    _options =
      type: 'GET'
    @_curd(_options, options)

  delete: (options) =>
    _options =
      type: 'DELETE'
    @_curd(_options, options)

  filter: (data, func) =>
    _.filter(data, func)

  _curd: (model_options, coustom_options) =>
    options = _.extend(model_options, coustom_options)
    @ajax(options)

  url_mapper: (options) =>
    '''options必选有type属性'''
    head_mapper =
      'GET': @fetch_url
      'POST': @new_url
      'PUT': @update_url
      'DELETE': @delete_url
    url = head_mapper[options['type']]
    if not head_mapper[options['type']]
      url = @url
    url

  get_url: (options) =>
    url = @url_mapper(options)
    Config['apiRoot'] + url + '/' + options['id']


  ajax: (options) =>
    '''options need id attr'''
    _options =
      url: @get_url(options)

    _options = _.extend(_options, @options)
    options = _.extend(_options, options)
    $.ajax(options)


class Collection extends Model
  '''model的list类型'''

  get_url: (options) =>
    url = @url_mapper(options)
    Config['apiRoot'] + url


class Controller
  '''Controller基类，每个Controller需要一个run方法'''
  constructor: ->
    @lib = new Lib
    @params = @lib.get_url_params()

  run: =>
    console.log 'run ' + @constructor.name


class Lib
  '''util'''
  get_root_url: ->
    # 网站根目录
    window.location.origin

  get_path_name: ->
    window.location.pathname

  get_url_params: ->
    query = window.location.search.substring(1)
    if not query
      return {}
    raw_vars = query.split("&")

    params = {}

    for v in raw_vars
      [key, val] = v.split("=")
      params[key] = decodeURIComponent(val)

    params

  get_url: =>
    @get_root_url + @get_path_name

  url_join_params:(url, params) ->
    p = ''
    for key,value of params
      if key
        p += "&#{key}=#{value}"
    if p
      url = "#{url}?#{p.substring(1)}"
    url

  refresh: ->
    window.location.reload()

  redirect_to: (uri) ->
    window.location.href = uri

  redirect_relative_to: (relative_uri) ->
    root = @get_root_url()
    window.location.href = root + relative_uri

  get_login_user: ->
    JSON.parse(window.localStorage.getItem('user'))

class Page

  get_cur_page: ->
    lib = new Lib
    param = lib.get_url_params()
    page = if 'page' not of param then 1 else param['page']

  get_data: (data) =>
    cur_page = @get_cur_page()
    start = (cur_page - 1) * Config['page_size']
    end = cur_page * Config['page_size']
    data[start...end]

  init_page_dom: (data, params,selector='#page-selection') =>
    lib = new Lib
    param = lib.get_url_params()
    cur_page = @get_cur_page()
    total = Math.floor((data.length - 1 ) / Config['page_size']) + 1
    if '' in params
      delete params['']
    $(selector).bootpag({total:total, page:cur_page}).on("page", (event, num) ->
      console.log 'run'
      pathname = lib.get_path_name()
      root_url = lib.get_root_url()
      params[Config['page_url_param']] = num
      next = lib.url_join_params(root_url+pathname, params)
      lib.redirect_to(next)
    )


active_nav = ->
  lib = new Lib
  user = lib.get_login_user()
  if not user or user['roleId'] != '管理员'
    $('.admin_href').remove()
  href = lib.get_path_name()
  li = jQuery('ul li a[href="'+href+'"]').parent()
  li.addClass('active')

init_datetimepicker = ->
  $(".form_datetime").datepicker(
    format: 'yyyy-MM-dd'
  )

confirm_dialog = (msg, func) ->
   if(confirm(msg))
     func()

delete_confirm = (func) ->
  confirm_dialog('确认删除？',func)

need_login = ->
  if not window.localStorage.getItem('user')
    lib = new Lib
    lib.redirect_relative_to('/auth/login.html')

public_common = ->

admin_common = ->
  $('.describe .row').hover(
    (e)->
      $('.admin-btn-tool', @).removeClass('hidden').addClass('show')
    ,
    (e)->
      $('.admin-btn-tool', @).removeClass('show').addClass('hidden')
  )



modal_form_reset = ->
  $('form.modal-content').resetForm()
  $('#info_modal .modal-title').html('表单')
  $modal_body = $('#info_modal form')
  $("input[name=sex][value="+Config['男']+"]", $modal_body).attr("checked","checked")
  $('select option', $modal_body).removeAttr('selected')
  $('textarea', $modal_body).html('')



class TeacherModel extends Model
  url: '/personinfo/teacher.do'


class UserCollection extends Collection
  url: '/user/user.do'
  new_url: '/user/create.do'

class LoginCollection extends Collection
  new_url: '/user/login.do'

class BookCollection extends Collection
  url: '/book/book.do'
  new_url: '/book/create.do'
  update_url: '/book/update.do'
  delete_url: '/book/delete.do'
  filter: (data, params) ->
    if 'is_out' of params
      return _.filter(data, (t) -> t['is_out']+'' == params['is_out'])
    else
      return data


class BookBorrowCollection extends Collection
  new_url: '/book/bookOut.do'


class BookReturnCollection extends Collection
  new_url: '/book/bookIn.do'

class TeacherCollection extends Collection
  url: '/personinfo/teacher.do'
  new_url: '/personinfo/create.do'
  update_url: '/personinfo/update.do'
  delete_url: '/personinfo/delete.do'

  filter: (data, params) ->
    if 'job' of params or 'degree' of params
      return _.filter(data, (t) ->
        if params['job']? and t['job'] == params['job']
          return true
        if params['degree']? and t['degree'] == params['degree']
          return true
        return false
      )
    else
      return data

class StudentCollection extends Collection
  url: '/personinfo/student.do'
  new_url: '/personinfo/create.do'
  update_url: '/personinfo/update.do'
  delete_url: '/personinfo/delete.do'

  filter: (data, params) ->
    if 'major' of params
      return _.filter(data, (t) -> t['major'] == params['major'])
    else
      return data


class EquipmentCollection extends Collection
  url: '/equipment/equipment.do'
  new_url: '/equipment/create.do'
  update_url: '/equipment/update.do'
  delete_url: '/equipment/delete.do'


class SlideCollection extends Collection
  url: '/img/image.do'
  update_url: '/img/update.do'

class SlideAdminCollection extends Collection
  url: '/imgs/images.do'
  new_url: '/imgs/create.do'
  delete_url: '/imgs/delete.do'


class TeacherController extends Controller
  run: =>
    super
    teacher = new TeacherCollection
    teacher.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        total_data = teacher.filter(total_data, @params)
        teachers = page.get_data(total_data)
        $describe = $('.describe')
        _.each(teachers, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          intro = t['t_intro']
          inputs = ""
          for attr,value of t
            inputs += "<input type='hidden' name=#{attr} value='#{value}' />"
          template = '''
              <div class='row'>
                <a data-toggle='modal' data-target='#info_modal'>
                  <img class='col-md-3' src='''+img_src+''' />
                  <p class='col-md-9'>''' + intro +
                '''
                  </p>
                  <form class='data'>
                    ''' + inputs +
                '''
                  </form>
                </a>
              </div>
          '''
          $describe.append(template)
        )
        $('.describe a').on('click',(e)->
          data = $('.data', @).serializeObject()
          $('#info_modal .modal-title').html(data['name'])
          $modal_body = $('#info_modal .modal-body')
          $('img', $modal_body).attr('src',
                Config['apiRoot'] + '/' + data['imagePath'])
          delete data['imagePath']
          for attr, value of data
            $(".#{attr}", $modal_body).html(value)
        )
        page.init_page_dom(total_data, @params)


class StudentController extends Controller
  run: ->
    super
    student = new StudentCollection
    student.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        total_data = student.filter(total_data, @params)
        students = page.get_data(total_data)
        $describe = $('.describe')
        _.each(students, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          intro = t['t_intro']
          inputs = ""
          for attr,value of t
            inputs += "<input type='hidden' name=#{attr} value='#{value}' />"
          template = '''
              <div class='row'>
                <a data-toggle='modal' data-target='#info_modal'>
                  <img class='col-md-3' src='''+img_src+''' />
                  <p class='col-md-9'>''' + intro +
                '''
                  </p>
                  <form class='data'>
                    ''' + inputs +
                '''
                  </form>
                </a>
              </div>
          '''
          $describe.append(template)
        )
        $('.describe a').on('click',(e)->
          data = $('.data', @).serializeObject()
          $('#info_modal .modal-title').html(data['name'])
          $modal_body = $('#info_modal .modal-body')
          $('img', $modal_body).attr('src',
                Config['apiRoot'] + '/' + data['imagePath'])
          delete data['imagePath']
          for attr, value of data
            $(".#{attr}", $modal_body).html(value)
        )
        page.init_page_dom(total_data, @params)


class LabController extends Controller

  run: =>
    super
    collection = new SlideCollection
    $carousel_indicators = $('.carousel-indicators')
    $carousel_inner = $('.carousel-inner')
    collection.fetch
      success: (data, status) =>
        total_data = data['data']
        index = 0
        for each in total_data
          console.log each
          console.log index
          indicator_template = "<li data-target='#lab_carousel' data-slide-to=#{index}></li>"
          console.log indicator_template
          $carousel_indicators.append(indicator_template)
          $carousel_inner.append('''
            <div class='item'>
              <img src=' '''+ Config['apiRoot'] + '/' + each['imagePath']+''' '/>
            </div>
          ''')
          index += 1
        $('.carousel-indicators li:first').addClass('active')
        $('.carousel-inner .item:first').addClass('active')
        $('.carousel').carousel()


class EquipmentController extends Controller

  run: =>
    super
    equipment = new EquipmentCollection
    equipment.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        equipments = page.get_data(total_data)
        $describe = $('.describe')
        _.each(equipments, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          intro = t['introduce']
          inputs = ""
          for attr,value of t
            inputs += "<input type='hidden' name=#{attr} value='#{value}' />"
          template = '''
              <div class='row'>
                <a data-toggle='modal' data-target='#info_modal'>
                  <img class='col-md-3' src='''+img_src+''' />
                  <p class='col-md-9'>''' + intro +
                '''
                  </p>
                  <form class='data'>
                    ''' + inputs +
                '''
                  </form>
                </a>
              </div>
          '''
          $describe.append(template)
        )
        $('.describe a').on('click',(e)->
          data = $('.data', @).serializeObject()
          $('#info_modal .modal-title').html(data['name'])
          $modal_body = $('#info_modal .modal-body')
          $('img', $modal_body).attr('src',
                Config['apiRoot'] + '/' + data['imagePath'])
          delete data['imagePath']
          for attr, value of data
            $(".#{attr}", $modal_body).html(value)
        )
        page.init_page_dom(total_data, @params)


class BookController extends Controller
  run: =>
    super
    book = new BookCollection
    borrow_collection = new BookBorrowCollection
    give_back_collection = new BookReturnCollection
    user = @lib.get_login_user()
    book.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        total_data = book.filter(total_data, @params)
        books = page.get_data(total_data)
        $describe = $('.describe')
        _.each(books, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          if t['is_out']
            if t['userId'] == user['id']
              button_template = "<button id='give_back_#{t['id']}' class='btn btn-warning give-back'>还书</button>"
            else
              button_template = "<button class='btn btn-error disabled'>已借出</button>"
          else
            button_template = "<button id='borrow_#{t['id']}' class='btn btn-success '>借阅</button>"
          template = '''
              <div class='row'>
                <span class='col-md-3'> <img src='''+img_src+''' /> </span>
                <span class='col-md-7'>
                  <span class='row'>书名: '''+"#{t['bookName']}"+''' </span>
                  <span class='row'>作者: '''+"#{t['author']}"+''' </span>
                  <span class='row'>出版社: '''+"#{t['publish']}"+''' </span>
                </span>
                <span class='col-md-2'>
                  ''' + button_template + '''
                </span>
              </div>
          '''
          $describe.append(template)
          $("#give_back_#{t['id']}", $describe).click( =>
            console.log 'abc'
            give_back_collection.new({
              data:
                id: t['id']
                userId: user['id']
              complete: (rep) ->
                if rep['status'] == 200
                  lib.refresh()
            })
          )
          $("#borrow_#{t['id']}", $describe).click( =>
            lib = new Lib
            borrow_collection.new({
              data:
                id: t['id']
                userId: user['id']
              complete: (rep) ->
                if rep['status'] == 200
                  lib.refresh()
            })
            #$(@).attr('method', 'POST').attr('action', borrow_collection.get_url({type:'POST'}))
            #borrow_collection.
            #$(@).ajaxSubmit( ->
              #lib = new Lib
              #lib.refresh()
            #)
          )
        )
        page.init_page_dom(total_data, @params)


class AdminTeacherController extends Controller
  run: =>
    super
    teacher = new TeacherCollection
    teacher.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        total_data = teacher.filter(total_data, @params)
        teachers = page.get_data(total_data)
        $describe = $('.describe')
        _.each(teachers, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          intro = t['t_intro']
          inputs = ""
          for attr,value of t
            inputs += "<input type='hidden' name='#{attr}'u value='#{value}' />"
          template = '''
              <div class='row'>
                <img class='col-md-3' src='''+img_src+''' />
                <p class='col-md-9'>''' + intro +
              '''
                </p>
                <form class='data' id='data_'''+t['id']+''''>
                  ''' + inputs +
              '''
                </form>
                <div class='admin-btn-tool hidden'>
                  <div class='btn-group btn-group-vertical'>
                    <button id='edit_'''+t['id']+'''' class='edit' data-toggle='modal' data-target='#info_modal'>
                      <span class='glyphicon glyphicon-edit'>
                        编辑
                      </span>
                    </button>
                    <button id='delete_'''+t['id']+''''class='delete'> 
                      <span class='glyphicon glyphicon-remove'>
                        删除
                      </span>
                    </button>
                  </div>
                </div>
              </div>
          '''
          $describe.append(template)
          $('#edit_'+t['id']).on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]") .val('edit')
            data = $('#data_'+t['id']).serializeObject()
            $('#info_modal .modal-title').html(data['name'])
            $modal_body = $('#info_modal .modal-body')
            $("input[name=id]", $modal_body).val(data['id'])
            $("input[name=gra_year]", $modal_body).val(data['gra_year'])
            $("input[name=name]", $modal_body).val(data['name'])
            $("input[name=sex]", $modal_body).removeAttr('checked')
            $("input[name=sex][value="+Config[data['sex']]+"]", $modal_body).attr("checked","checked")
            $('select option[value='+data['degree']+']', $modal_body).attr('selected','selected')
            $('select option[value='+data['job']+']', $modal_body).attr('selected','selected')
            $("textarea[name=T_intro]", $modal_body).html(data['t_intro'])
            $("textarea[name=T_introduce]", $modal_body).html(data['t_introduce'])
          )
          $('#delete_'+t['id']).on('click',(e)=>
            delete_confirm(()=>
              teacher.delete(
                data:
                  id: t['id']
                method: 'POST'
                success: @lib.refresh()
              )
            )
          )
        )
        $('.describe .add').on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]").val('add')
        )
        page.init_page_dom(total_data, @params)
        admin_common()

    $('form').submit((e) ->
      data = $(@).serializeObject()
      form_type = data['form_type']
      delete data['form_type']
      switch form_type
        when 'add'
          $(@).attr('method', 'POST').attr('action', teacher.get_url({type:'POST'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        when 'edit'
          $(@).attr('method', 'POST') .attr('action', teacher.get_url({type:'PUT'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        else
          console.log 'what are you trying?'

      $('.modal').modal('hide')
      return false
    )
    @

class AdminStudentController extends Controller
  run: =>
    super
    student = new StudentCollection
    student.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        total_data = student.filter(total_data, @params)
        students = page.get_data(total_data)
        $describe = $('.describe')
        _.each(students, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          intro = t['t_intro']
          inputs = ""
          for attr,value of t
            inputs += "<input type='hidden' name='#{attr}'u value='#{value}' />"
          template = '''
              <div class='row'>
                <img class='col-md-3' src='''+img_src+''' />
                <p class='col-md-9'>''' + intro +
              '''
                </p>
                <form class='data' id='data_'''+t['id']+''''>
                  ''' + inputs +
              '''
                </form>
                <div class='admin-btn-tool hidden'>
                  <div class='btn-group btn-group-vertical'>
                    <button id='edit_'''+t['id']+'''' class='edit' data-toggle='modal' data-target='#info_modal'>
                      <span class='glyphicon glyphicon-edit'>
                        编辑
                      </span>
                    </button>
                    <button id='delete_'''+t['id']+''''class='delete'> 
                      <span class='glyphicon glyphicon-remove'>
                        删除
                      </span>
                    </button>
                  </div>
                </div>
              </div>
          '''
          $describe.append(template)
          $('#edit_'+t['id']).on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]") .val('edit')
            data = $('#data_'+t['id']).serializeObject()
            $('#info_modal .modal-title').html(data['name'])
            $modal_body = $('#info_modal .modal-body')
            $("input[name=id]", $modal_body).val(data['id'])
            $("input[name=gra_year]", $modal_body).val(data['gra_year'])
            $("input[name=name]", $modal_body).val(data['name'])
            $("input[name=sex]", $modal_body).removeAttr('checked')
            $("input[name=sex][value="+Config[data['sex']]+"]", $modal_body).attr("checked","checked")
            $('select option[value='+data['degree']+']', $modal_body).attr('selected','selected')
            $('select option[value='+data['job']+']', $modal_body).attr('selected','selected')
            $("textarea[name=T_intro]", $modal_body).html(data['t_intro'])
            $("textarea[name=T_introduce]", $modal_body).html(data['t_introduce'])
          )
          $('#delete_'+t['id']).on('click',(e)=>
            delete_confirm(()=>
              student.delete(
                data:
                  id: t['id']
                method: 'POST'
                success: @lib.refresh()
              )
            )
          )
        )
        $('.describe .add').on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]").val('add')
        )
        page.init_page_dom(total_data, @params)
        admin_common()

    $('form').submit((e) ->
      data = $(@).serializeObject()
      form_type = data['form_type']
      delete data['form_type']
      switch form_type
        when 'add'
          $(@).attr('method', 'POST').attr('action', student.get_url({type:'POST'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        when 'edit'
          $(@).attr('method', 'POST') .attr('action', student.get_url({type:'PUT'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        else
          console.log 'what are you trying?'

      $('.modal').modal('hide')
      return false
    )
    @


class AdminLabController extends Controller
  run: ->
    super
    slideView = new SlideCollection
    slideView.fetch
      success: (data, status) =>
        total_data = data['data']
        image_path_list = _.map(total_data, (each) ->
          each['imagePath']
        )
        $('.config').html( image_path_list.join('\n'))
    slide = new SlideAdminCollection
    slide.fetch
      success: (data, status) =>
        $pictures = $('.pictures')
        total_data = data['data']
        index = 0
        for each in total_data
          imagePath = Config['apiRoot'] + '/' + each['imagePath']
          template ='''
            <div class='col-md-3 pic'>
              <a class='detail' href='#'>
                <img src=''' + "#{imagePath}" +''' />
                <input type='hidden' value=''' + "#{each['imagePath']}" +''' />
              <a>
              <div class='admin-btn-tool hidden'>
                <div class='btn-group btn-group-vertical'>
                  <button id='delete_'''+each['id']+''''class='delete' data-id='''+each['id']+'''>
                    <span class='glyphicon glyphicon-remove'>
                      删除
                    </span>
                  </button>
                </div>
              </div>
          '''
          $pictures.append(template)
          $("#delete_#{each['id']}").click( ->
            slide.delete({
              data:
                id: $(@).attr('data-id')
              method: 'POST'
              success: ->
                lib = new Lib
                lib.refresh()
            })
          )
          index += 1

        $('.pic .detail').click( (e) ->
          $cur = $(e.currentTarget)
          imagePath = $('input', $cur).val()
          old = $('textarea').val()
          $('textarea').val(old+'\n'+imagePath)
          return false
        )
        $('.pic').hover(
          (e)->
            $('.admin-btn-tool', @).removeClass('hidden').addClass('show')
          ,
          (e)->
            $('.admin-btn-tool', @).removeClass('show').addClass('hidden')
        )

    $('form.slide-config').submit((e) ->
      $(@).attr('method', 'POST') .attr('action', slideView.get_url({type:'PUT'}))
      $(@).ajaxSubmit( ->
        lib = new Lib
        lib.refresh()
      )
      return false
    )
    $('form.modal-content').submit((e) ->
      $(@).attr('method', 'POST') .attr('action', slide.get_url({type:'POST'}))
      $(@).ajaxSubmit( ->
        lib = new Lib
        lib.refresh()
      )
      return false
    )


class AdminEquipmentController extends Controller
  run: =>
    super
    equipment = new EquipmentCollection
    equipment.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        equipments = page.get_data(total_data)
        $describe = $('.describe')
        _.each(equipments, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          intro = t['introduce']
          inputs = ""
          for attr,value of t
            inputs += "<input type='hidden' name='#{attr}'u value='#{value}' />"
          template = '''
              <div class='row'>
                <img class='col-md-3' src='''+img_src+''' />
                <p class='col-md-9'>''' + intro +
              '''
                </p>
                <form class='data' id='data_'''+t['id']+''''>
                  ''' + inputs +
              '''
                </form>
                <div class='admin-btn-tool hidden'>
                  <div class='btn-group btn-group-vertical'>
                    <button id='edit_'''+t['id']+'''' class='edit' data-toggle='modal' data-target='#info_modal'>
                      <span class='glyphicon glyphicon-edit'>
                        编辑
                      </span>
                    </button>
                    <button id='delete_'''+t['id']+''''class='delete'> 
                      <span class='glyphicon glyphicon-remove'>
                        删除
                      </span>
                    </button>
                  </div>
                </div>
              </div>
          '''
          $describe.append(template)
          $('#edit_'+t['id']).on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]") .val('edit')
            data = $('#data_'+t['id']).serializeObject()
            $('#info_modal .modal-title').html(data['name'])
            $modal_body = $('#info_modal .modal-body')
            $("input[name=id]", $modal_body).val(data['id'])
            $("input[name=name]", $modal_body).val(data['name'])
            $("textarea[name=introduce]", $modal_body).html(data['introduce'])
          )
          $('#delete_'+t['id']).on('click',(e)=>
            delete_confirm(()=>
              equipment.delete(
                data:
                  id: t['id']
                method: 'POST'
                success: @lib.refresh()
              )
            )
          )
        )
        $('.describe .add').on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]").val('add')
        )
        page.init_page_dom(total_data, @params)
        admin_common()

    $('form').submit((e) ->
      data = $(@).serializeObject()
      form_type = data['form_type']
      delete data['form_type']
      switch form_type
        when 'add'
          $(@).attr('method', 'POST').attr('action', equipment.get_url({type:'POST'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        when 'edit'
          $(@).attr('method', 'POST') .attr('action', equipment.get_url({type:'PUT'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        else
          console.log 'what are you trying?'

      $('.modal').modal('hide')
      return false
    )
    @


class DiscuzController extends Controller
  run: ->
    super
    init_datetimepicker()
    $('#page-selection').bootpag({total:10}).on("page", (event, num) ->
    )

class DiscuzArticleController extends Controller
  run: ->
    super
    lib = new Lib
    params = lib.get_url_params()
    id = params['id']
    console.log id


class AdminBookController extends Controller
  run: =>
    super
    book = new BookCollection
    book.fetch
      success: (data, status) =>
        page = new Page
        total_data = data['data']
        total_data = book.filter(total_data, @params)
        books = page.get_data(total_data)
        $describe = $('.describe')
        _.each(books, (t)->
          img_src = Config['apiRoot'] + '/' + t['imagePath']
          intro = t['t_intro']
          inputs = ""
          for attr,value of t
            inputs += "<input type='hidden' name='#{attr}'u value='#{value}' />"
          template = '''
              <div class='row'>
                <span class='col-md-3'> <img src='''+img_src+''' /> </span>
                <span class='col-md-7'>
                  <span class='row'>书名: '''+"#{t['bookName']}"+''' </span>
                  <span class='row'>作者: '''+"#{t['author']}"+''' </span>
                  <span class='row'>出版社: '''+"#{t['publish']}"+''' </span>
                </span>
                <form class='data' id='data_'''+t['id']+''''>
                  ''' + inputs +
              '''
                </form>
                <div class='admin-btn-tool hidden'>
                  <div class='btn-group btn-group-vertical'>
                    <button id='edit_'''+t['id']+'''' class='edit' data-toggle='modal' data-target='#info_modal'>
                      <span class='glyphicon glyphicon-edit'>
                        编辑
                      </span>
                    </button>
                    <button id='delete_'''+t['id']+''''class='delete'> 
                      <span class='glyphicon glyphicon-remove'>
                        删除
                      </span>
                    </button>
                  </div>
                </div>
              </div>
          '''
          $describe.append(template)
          $('#edit_'+t['id']).on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]") .val('edit')
            data = $('#data_'+t['id']).serializeObject()
            console.log data
            $('#info_modal .modal-title').html(data['name'])
            $modal_body = $('#info_modal .modal-body')
            $("input[name=id]", $modal_body).val(data['id'])
            $("input[name=bookName]", $modal_body).val(data['bookName'])
            $("input[name=publish]", $modal_body).val(data['publish'])
            $("input[name=author]", $modal_body).val(data['author'])
          )
          $('#delete_'+t['id']).on('click',(e)=>
            delete_confirm(()=>
              book.delete(
                data:
                  id: t['id']
                method: 'POST'
                success: @lib.refresh()
              )
            )
          )
        )
        $('.describe .add').on('click',(e)->
            modal_form_reset()
            $("input[name=form_type]").val('add')
        )
        page.init_page_dom(total_data, @params)
        admin_common()

    $('form').submit((e) ->
      data = $(@).serializeObject()
      form_type = data['form_type']
      delete data['form_type']
      switch form_type
        when 'add'
          $(@).attr('method', 'POST').attr('action', book.get_url({type:'POST'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        when 'edit'
          $(@).attr('method', 'POST') .attr('action', book.get_url({type:'PUT'}))
          $(@).ajaxSubmit( ->
            lib = new Lib
            lib.refresh()
          )
        else
          console.log 'what are you trying?'

      $('.modal').modal('hide')
      return false
    )
    @


class RegisterController extends Controller
  run: =>
    super
    collection = new UserCollection
    $('form').submit((e) ->
      data = $(@).serializeObject()
      $(@).attr('method', 'POST').attr('action', collection.get_url({type:'POST'}))
      $(@).ajaxSubmit( (rep)->
        if rep['errcode']  == 1
          alert('用户名已被注册')
        else
          lib = new Lib
          lib.redirect_relative_to('/auth/login.html')
      )
      return false
    )

class LoginController extends Controller
  run: =>
    super
    collection = new LoginCollection
    $('form').submit((e) ->
      data = $(@).serializeObject()
      $(@).attr('method', 'POST').attr('action', collection.get_url({type:'POST'}))
      $(@).ajaxSubmit( (rep)->
        if not rep['errcode']
          user = rep['data']
          # for safe
          delete user['passwd']
          window.localStorage.setItem('user', JSON.stringify(user))
          lib = new Lib
          lib.redirect_relative_to('/')
        else
          alert rep['errmsg']
      )
      return false
    )

class LogoutController extends Controller
  run: =>
    super
    window.localStorage.removeItem('user')
    @lib.redirect_relative_to('/')

Router =
  '/': undefined
  '/teacher.html': new TeacherController
  '/lab.html': new LabController
  '/student.html': new StudentController
  '/equipment.html': new EquipmentController
  '/book.html': new BookController
  '/admin/teacher.html': new AdminTeacherController
  '/admin/lab.html': new AdminLabController
  '/admin/student.html': new AdminStudentController
  '/admin/equipment.html': new AdminEquipmentController
  '/admin/book.html': new AdminBookController
  '/discuz.html': new DiscuzController
  '/discuz/article.html': new DiscuzArticleController
  '/auth/register.html': new RegisterController
  '/auth/login.html': new LoginController
  '/auth/logout.html': new LogoutController

NotNeedLoginList = ['/auth/register.html', '/auth/login.html']

$(
  active_nav()
  lib = new Lib
  href = lib.get_path_name()
  href = href.split('?')[0]
  if href of Router and href not in NotNeedLoginList
    need_login()
  controller = Router[href]
  if controller
    controller.run()
)
